Thumb

What are Access Modifiers?

1/7/2020 6:35:44 AM

Access Modifiers in C# are given access permission to get and set value. Basically, C# allow the five type of access modifiers. Depend of access modifier to set the access permission each method, class, property etc. C# access modifiers nothing but a key word. This is the important we can set the access permission of the specific Aria. Now given bellow the example access modifier code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectTest
{
    public class PublicClass
    {
       public int _value;
    }
    public class InternalClass
    {
        internal int _value;
    }
    public class ProtectedClass
    {
        protected int _value;
        public int AssinValue
        {
            get { return _value; }
            set { _value = value; }
        }
    }
    public class PrivetClass
    {
        private int _value;
        public int AssinValue
        {
            get { return _value; }
            set { _value = value; }
        }
    }
    public class ProtectedInternal
    {
        protected internal int _value;
    }

    class AccessModifiers
    {
        static void Main()
        {
            PublicClass pc = new PublicClass();
            pc._value = 15;
            Console.WriteLine("I am from public : "+ pc._value);
            InternalClass ic = new InternalClass();
            ic._value = 10;
            Console.WriteLine("I am from internal : "+ic._value);
            ProtectedClass prc = new ProtectedClass();
            prc.AssinValue = 22;
            Console.WriteLine("I am from protected : " + prc.AssinValue);
            PrivetClass pric = new PrivetClass();
            pric.AssinValue = 24;
            Console.WriteLine("I am from private : " + pric.AssinValue);
            ProtectedInternal proInt = new ProtectedInternal();
            proInt._value = 33;
            Console.WriteLine("I am from protected internal : " + proInt._value);
            Console.ReadKey();
        }

    }

}

In this code I will show to work access modifier permission to access the method, class and property etc.

Public: public access modifier allows to access from anywhere of the project. It is publicly available.

Internal: Internal is another key word for access the project. Under solution C# allow to multipole project. Then Internal can’t access to another project. It allows to only its own project.

Privet: privet is access to won class, it can’t access to other class. If this class is same project but privet can’t access.

Protected: This key word work like privet but it also some special to privet. It accesses only inheritance by the class or when we inherit and use Base key word then we access this modifier. 

Protected Internal: also, C# access modifier it is special type. It works protected and internal combination.